$(function () {
    layui.use(['laydate', 'table', 'form', 'layer', 'laytpl', 'formSelects'], function () {
        var table = layui.table,
            form = layui.form,
            layer = layui.layer,
            laytpl = layui.laytpl,
            formSelects = layui.formSelects;
        var tableIns = null;
        form.render();
        getGatewayData();
        function getGatewayData(){
            $.ajax({
                type: "GET",
                url: ctx + "/gateway/getAll.do",
                data: {},
                dataType: "json",
                success: function (result) {
                    var resData = result;
                    var tableData = resData.concat();
                    renderGateway(tableData);
                }
            });
        }

        function renderGateway(tableData) {
            var getTpl = $('#gateway-tpl').html();
            laytpl(getTpl).render(tableData, function (html) {
                $('.gateway ul').html(html);
            });
            var lis = $('.gateway ul li.layui-row');
            for (var i = 0; i < lis.length; i++) {
                var id = parseInt($(lis[i]).attr('value'));
                var tbId = 'tbId' + id;
                renderTable(tbId, id,tableData);
            }
        }

        function renderTable(tbId, gatewayId,tableData) {
            var devlist = tableData.filter(function (item) {
                return item.gatewayId == gatewayId
            })[0].meters;
            var len = Math.ceil(devlist.length / 2),
                left = devlist.slice(0, len),
                right = devlist.slice(len);
            var tbId = 'tbId' + gatewayId;
            devList(tbId + '-l', left);
            if(devlist.length > 1){
                devList(tbId + '-r', right);
            }
        }

        $('.gateway').on('click', 'li .gateway-list', function () {
            var li = $(this).parent();
            var gatewayId = li.attr('value');
            li.toggleClass('open-up');
            li.find('.dev-list').toggleClass('hide');
            table.resize('tbId' + gatewayId + '-l');
            table.resize('tbId' + gatewayId + '-r');
        });

        function devList(id, data) {
            table.render({
                elem: '#' + id
                , id: id
                , cellMinWidth: 60
                , data: data
                , skin: 'row'
                , cols: [[
                    {field: 'anotherName', title: '设备名称'}
                    , {field: 'state', title: '状态', templet: '#lightTpl', width: 60}
                    , {field: 'readerCode', title: 'ID'}
                ]]
                , done: function(){

                }
            });
        }

    });
});
